# 导入相关库和模块
from fastapi import APIRouter, Depends, HTTPException, Query, Request
from sqlalchemy.orm import Session
from database import SessionLocal
import sys
from admin.base_controller import BaseController
from config.logging import logger
from services.admin.menu_api_service import MenuApiService


# 定义获取数据库会话的依赖
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


# 定义控制器类
class MenuApi(BaseController):
    def __init__(self):
        super().__init__()
        self.router = APIRouter()

    async def create_menu(self, data: dict, db: Session = Depends(get_db)):
        """
        创建菜单
        """
        service = MenuApiService(db)
        result = await service.create_menu(data)
        return self.success_response(data=result, message="success")

    async def menu_list(self, db: Session = Depends(get_db), page: int = Query(default=1, ge=1),
                        limit: int = Query(default=20, ge=1)):
        """
        菜单列表
        """
        service = MenuApiService(db)
        limit = 200
        result = await service.menu_list(page, limit)
        return self.success_response(data=result, message="success")

    async def menu_detail(self, menuId: int, db: Session = Depends(get_db)):
        """
        菜单详情
        """
        service = MenuApiService(db)
        result = await service.menu_detail(menuId)
        return self.success_response(data=result, message="success")

    async def update_menu(self, menuId: int, data: dict, db: Session = Depends(get_db)):
        """
        更新菜单
        """
        service = MenuApiService(db)
        result = await service.update_menu(menuId, data)
        return self.success_response(data=result, message="success")

    async def delete_menu(self, menuId: str, db: Session = Depends(get_db)):
        """
        删除菜单
        """
        service = MenuApiService(db)
        result = await service.delete_menu(menuId)
        return self.success_response(data=result, message="success")

    async def user_menu(self, request: Request, db: Session = Depends(get_db)):
        """
        用户菜单
        """
        service = MenuApiService(db)
        result = await service.user_menu(request.state.user)
        return self.success_response(data=result, message="success")

# 使用
menu_api = MenuApi()
router = menu_api.router
